<template>
  <div class="box">
    <div class="main">
      <div class="sub-title">
        <img src="@/assets/images/online.png" alt="" />
        <div class="navigation">
          <div
            v-for="(item, index) in items"
            :key="index"
            class="navigation-item"
            :class="{ active: index === activeIndex }"
            @click="handleChange(item, index)"
            ref="itemRefs"
          >
            {{ item.name }}
          </div>
          <div
            class="navigation-underline"
            :class="{ active: activeIndex !== -1 }"
            :style="underlineStyle"
            ref="underlineRef"
          ></div>
        </div>
      </div>

      <div class="f fw" v-show="activeIndex == 0">
        <div
          v-for="(item, index) in courseList"
          :key="index"
          class="course-item pointer"
          @click="goPath('/learnVideo', item.id)"
        >
          <img :src="item.courseCover" alt="" width="272" height="152" />
          <div class="f14 pl10 pr10 pt13 pb10">
            <div class="mb10 tem">
              {{ item.courseName + "（" + item.totalHours + "课时）" }}
            </div>
            <div class="course-content tem3">
              {{ item.courseDesc }}
            </div>
          </div>
        </div>
      </div>
      <div class="f fw" v-show="activeIndex == 1">
        <div
          v-for="(item, index) in examList"
          :key="index"
          class="course-item pointer"
          @click="goPath('/examination')"
        >
          <img
            :src="(item.fileInfos && item.fileInfos[0].url) || defaultImg"
            alt=""
            width="100%"
            height="152"
          />
          <div class="f14 pl10 pr10 pt13 pb20">
            <div class="mb10 tem">{{ item.paperName }}</div>
            <div class="course-content tem3">
              {{ item.exameTitle }}
            </div>
          </div>
        </div>
      </div>
    </div>
  </div>
</template>

<script setup lang="ts">
import { useRouter } from "vue-router";
import { getCourseList, getPaperList } from "@/api/home";
import defaultImg from "@/assets/images/defaultImg.png";
import { useAuthStore } from "@/store/auth";

const route = useRouter();
const authStore = useAuthStore();

const baseUrl = import.meta.env.VITE_APP_STATIC_BASE_API;

const courseList = ref([]);
const examList = ref([]);
const activeIndex = ref(0);
const items = ref([
  { name: "课程", type: 1 },
  { name: "题库", type: 2 },
]);
const underlineStyle = ref({
  transform: "translateX(0)",
});
const itemRefs = ref([]);
const underlineRef = ref(null);

const updateUnderline = () => {
  // 获取标题的宽度，减去下划线的宽度除以2，可以使下划线在标题下居中显示
  const item = itemRefs.value[activeIndex.value];
  const underline = underlineRef.value;
  let newLeft = Number(item.offsetWidth - underline.offsetWidth) / 2;
  if (item && underline) {
    const { offsetLeft } = item;
    underlineStyle.value = {
      transform: `translateX(${offsetLeft + newLeft}px)`,
    };
  }
};

const getCourseListData = () => {
  getCourseList({ examPublishStatus: 2 }).then((res) => {
    courseList.value = res.rows?.length > 8 ? res.rows.slice(0, 8) : res.rows;
    // courseList.value = res.rows;
  });
};

const getPaperListData = () => {
  getPaperList()
    .then((res) => {
      const arr = res.rows.filter((item) => item.exameType == 1);
      examList.value = arr?.length > 8 ? arr.slice(0, 8) : arr;
    })
    .catch(() => {
      route.push("/login");
    });
};

const handleChange = (item, index) => {
  if (item.type == 2) {
    const token = authStore.token;
    if (!token) {
      route.push("/login");
      return false;
    } else {
      getPaperListData();
    }
  }
  activeIndex.value = index;
};

watch(activeIndex, () => {
  updateUnderline();
});

onMounted(() => {
  updateUnderline();
  getCourseListData();
});

const goPath = (path, id) => {
  route.push({
    path: path,
    query: {
      id: id,
    },
  });
};
</script>
<style lang="scss" scoped>
.box {
  background: #f5f7fa;
  .main {
    width: 1154px;
    margin: 0 auto;
    padding: 30px 0 15px;
    .sub-title {
      display: flex;
      align-items: flex-start;
      margin-bottom: 30px;
      img {
        width: 161px;
        height: 26px;
      }
      .navigation {
        display: flex;
        align-items: center;
        justify-content: space-around;
        position: relative;
        padding: 0 20px;
        font-size: 16px;
        font-weight: bold;
        margin-top: 5px;
      }

      .navigation-item {
        cursor: pointer;
        padding: 0 15px 10px;
      }

      .navigation-item.active {
        color: #f00;
      }

      .navigation-underline {
        /* 下划线的宽度 */
        width: 25px;
        height: 3px;
        border-radius: 2px;
        position: absolute;
        bottom: 0;
        left: 0;
        background-color: #f00;
        transition: all 0.3s ease-in-out;
      }

      .navigation-underline.active {
        transform: translateY(-3px);
      }
    }

    // 内容
    .course-item {
      width: 272px;
      height: 282px;
      background: #ffffff;
      border-radius: 10px;
      overflow: hidden;
      color: #6e747a;
      margin-right: 22px;
      margin-bottom: 22px;
      &:nth-child(4n) {
        margin-right: 0;
      }
      .course-content {
        line-height: 24px;
        opacity: 0.7;
      }
    }
  }
}
</style>
